<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/28
 * Time: 10:03
 */
namespace app\api\service;

use app\lib\exception\TokenException;
use think\Cache;
use think\Exception;
use think\Request;

class Token {

    public static function generateToken(){
//        32位随机数
        $randChars = getRandChar(32);
//        用三组字符串，进行MD5加密
        $timestamp = $_SERVER['REQUEST_TIME'];
        $salt = config('wx.token_salt');
        return md5($randChars.$timestamp.$salt);
    }

    /**
     *根据key值 获取缓存中相应的数据
     * @param $key
     */
    public static function getCurrentTokenVar($key){
        $request = Request::instance()->header('token');
        $values = cache($request);
//        print_r($values);
        if(empty($values)){
            throw new TokenException([
                'msg'=>'获取缓存数据失败，token值是否有效',
                'errorCode'=>10005
            ]);
        }else{
            if(!is_array($values)){
                $values = json_decode($values,true);
            }
            if(!array_key_exists($key,$values)){
                throw new Exception('尝试获取token变量不存在');
            }
            return $values[$key];
        }
    }

    /**
     * 根据token获取uid
     */
    public static function getCurrentUid(){
        return self::getCurrentTokenVar('uid');
    }


    public static function isValidOperate($checkUid){
        if(!$checkUid){
            throw new Exception('uid不能为空');
        }
        $nowUid = self::getCurrentUid();
        if($nowUid == $checkUid){
            return true;
        }
        return false;
    }

    /**
     * 判断待支付订单与当着用户是否匹配
     * @param $token
     * @return bool
     */
    public static function verifyToken($token)
    {
        $exist = cache($token);
        if($exist){
            return true;
        }
        else{
            return false;
        }
    }

}